import 'package:ac/api/ac_urls.dart';
import 'package:ac/common/ac_chat_util.dart';
import 'package:ac/common/ac_more_util.dart';
import 'package:ac/data/ac_user_manager.dart';
import 'package:ac/model/ac_blogger_model.dart';
import 'package:ac/page/ac_message/ac_message_logic.dart';
import 'package:ac/page/ac_post_list/ac_post_detail/ac_post_detail_logic.dart';
import 'package:ac/route/ac_route_pages.dart';
import 'package:get/get.dart';
import 'package:rongcloud_im_wrapper_plugin/rongcloud_im_wrapper_plugin.dart';

import '../../model/ac_login_model.dart';
import '../ac_post_list/ac_post_list_logic.dart';
import 'ac_user_detail_state.dart';

class AcUserDetailLogic extends GetxController {
  final AcUserDetailState state = AcUserDetailState();
  final blogger = Rxn<AcBloggerModel>();
  late final AcMoreUtil moreUtil;

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
    _initData();
  }

  void _initData() {
    for (var element in AcUserManager.bloggerList) {
      if (element.userInfo?.userId == Get.arguments) {
        blogger.value = element;
        break;
      }
    }
    moreUtil = AcMoreUtil(
      blogger.value!.userInfo!,
      blogger.refresh,
      blockCallback: () {
        Get.back();
        if (Get.parameters['from'] == 'post_detail') {
          Get.back();
        }
      },
    );
  }

  Future<void> follow() async {
    var res = await AcUrls.follow
        .post(data: {"followUserId": blogger.value!.userInfo?.userId});
    if (res?["code"] == 0) {
      _updateUserInfo(true);
    }
  }

  Future<void> unFollow() async {
    var res = await AcUrls.unFollow
        .post(data: {"followUserId": blogger.value!.userInfo?.userId});
    if (res?["code"] == 0) {
      _updateUserInfo(false);
    }
  }

  void _updateUserInfo(bool isFriend) {
    blogger.value!.userInfo!.isFriend = isFriend;
    blogger.refresh();
    AcUserManager.updateBloggerUserInfo(blogger.value!.userInfo!);
    if (Get.isRegistered<AcPostDetailLogic>()) {
      Get.find<AcPostDetailLogic>().refreshUserInfo();
    }
    if (Get.isRegistered<AcPostListLogic>()) {
      Get.find<AcPostListLogic>().refreshUserInfo();
    }
  }

  void more() {
    moreUtil.show();
  }

  Future<void> chat() async {
    AcChatUtil.openChat(blogger.value!.userInfo!.userId!);
  }
}
